package com.etxxy.common.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.DOMReader;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @category xml操作工具类
 * 
 * @author yiz
 * @date 2016年5月12日 上午8:50:30
 * @version 1.0.0 
 * @copyright pycredit.cn 
 */
public class XMLParseUtil {

	private static final Logger logger = LoggerFactory.getLogger(XMLParseUtil.class);

	public static Document getDocument(String xml, String encode) {
		Document document = null;
		try {
			SAXReader reader = new SAXReader();
			InputStream in = null;
			InputStreamReader strInStream = null;
			if (StringUtils.isBlank(encode)) {
				in = new ByteArrayInputStream(xml.getBytes(encode));
				strInStream = new InputStreamReader(in, encode);
			} else {
				in = new ByteArrayInputStream(xml.getBytes());
				strInStream = new InputStreamReader(in);
			}

			document = reader.read(strInStream);
		} catch (Exception e) {
			logger.error("XML不合法! :e={}", e);
		}
		return document;
	}

	/**
	 * @category document转为Map
	 * @param document
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> Dom2Map(Document document) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (document == null) {
			return map;
		}
		Element root = document.getRootElement();
		for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
			Element e = (Element) iterator.next();
			List list = e.elements();
			if (list.size() > 0) {
				map.put(e.getName(), Elem2Map(e));
			} else
				map.put(e.getName(), e.getText());
		}
		return map;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map Elem2Map(Element element) {
		Map map = new HashMap();
		List list = element.elements();
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Element iter = (Element) list.get(i);
				List mapList = new ArrayList();

				if (iter.elements().size() > 0) {
					Map m = Elem2Map(iter);
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(m);
						}
						if (obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = (List) obj;
							mapList.add(m);
						}
						map.put(iter.getName(), mapList);
					} else
						map.put(iter.getName(), m);
				} else {
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(iter.getText());
						}
						if (obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = (List) obj;
							mapList.add(iter.getText());
						}
						map.put(iter.getName(), mapList);
					} else
						map.put(iter.getName(), iter.getText());
				}
			}
		} else
			map.put(element.getName(), element.getText());
		return map;
	}

	/**
	 * @category 得到根节点
	 * @param xml
	 * @return
	 */
	public static Element getRootElement(String xml) {
		if (StringUtils.isBlank(xml)) {
			return null;
		}
		Document document = null;
		try {
			document = DocumentHelper.parseText(xml);
		} catch (DocumentException e) {
			logger.error("转xml出现异常e={}", e);
		}
		Element element = getRootElement(document);
		return element;
	}

	/**
	 * @category 得到根节点
	 * @param document
	 * @return
	 */
	public static Element getRootElement(Document document) {
		if (null == document) {
			return null;
		}
		Element element = document.getRootElement();
		return element;
	}

	/**
	 * @category 将w3cDocument转为Dom4J
	 * @param document
	 * @return
	 */
	public static Document parseFromW3C(org.w3c.dom.Document document) {
		if (null == document) {
			return null;
		}
		return new DOMReader().read(document);
	}

	/**
	 * @category 判断对象是否是字符串
	 * @param obj
	 * @return
	 */
	public static boolean isStr(Object obj) {
		return null == obj ? false : String.class.isAssignableFrom(obj.getClass());
	}

	/**
	 * @category 判断对象时否是dom
	 * @param obj
	 * @return
	 */
	public static boolean isDom(Object obj) {
		return null == obj ? false : org.w3c.dom.Document.class.isAssignableFrom(obj.getClass());
	}
}
